import React, { useEffect, useState } from 'react';
import address from '../address';
import { connect } from 'react-redux';
import { getApplist,getFunList } from '../sysRedux/getAppList';
import { Menu, Modal, Form, Input} from 'antd';
import { MailOutlined, PlusCircleOutlined,RestOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import { withRouter, Switch, Route, NavLink } from 'react-router-dom';
import FunDetails from './FunDetails';
const { confirm } = Modal;
let token = ''||localStorage.getItem('token');

const CollectionCreateForm = ({ visible, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
        <Modal
            visible={visible}
            title="添加功能"
            okText="添加"
            cancelText="取消"
            onCancel={onCancel}
            onOk={() => {
                form
                    .validateFields()
                    .then((values) => {
                        form.resetFields();
                        onCreate(values);
                    })
                    .catch((info) => {
                        console.log('Validate Failed:', info);
                    });
            }}
        >
            <Form
                form={form}
                layout="vertical"
                name="form_in_modal"
                initialValues={{
                    modifier: 'public',
                }}
            >
                <Form.Item
                    name="title"
                    label="功能名称"
                    rules={[
                        {
                            required: true,
                            message: '请输入功能名称!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item 
                    name="description" 
                    label="图标名称"
                    rules={[
                        {
                            required: true,
                            message: '请输入图标名称!',
                        },
                    ]}
                >
                    <Input type="textarea" />
                </Form.Item>
            </Form>
        </Modal>
    );
};

const AppDetail = (props) => {
    let recvParam;
    if(props.location.state){
        recvParam = props.location.state;
        console.log(recvParam);
        sessionStorage.setItem('data',JSON.stringify(recvParam));
    }else{
        recvParam = sessionStorage.getItem('data');
    }
    const [visible, setVisible] = useState(false);
    useEffect(() => {
        props.dispatch(getApplist());
        props.dispatch(getFunList(recvParam.appname))
    }, []);
    const routes = props.appFunList.map((item) => {
        let obj = {
            path: props.match.path + '/' + item.ename.split('_')[0] + '/' + item.ename.split('_')[1],
            component: FunDetails
        };
        return obj;
    });
    let len = routes.length+1;
    const onCreate = (values) => {
        // console.log('Received values of form: ', values);
        let appname = props.location.pathname.split('/')[3];
        let ename = 'fun'+len
        let data={
            "name":values.title,
            "iconname":values.description,
            "appname":appname,
            "ename":ename,
        }

        fetch(address+'/admin/uploadappFunc', {
        method : 'POST',
        mode : 'cors',
        headers: {
            'authorization':token
        },
        body : JSON.stringify(data)
    }).then(res => {
        if (res.ok) {
            return res.text()
        } else {
            throw new Error(`status: ${res.status}`)
        }
        }, err => {

    }).then(d => {
        if (d === undefined || d === '') {
            return
        }
        
    })
    .catch(err => {
        console.log(err)
    })

        setVisible(false);
    };

    const delApp = () =>{
        let appname = props.location.pathname.split('/')[3];
        fetch(address+'/admin/deleteApp', {
            method : 'DELETE',
            mode : 'cors',
            headers: {
                'authorization':token
            },
            body : appname
        }).then(res => {
            if (res.ok) {
                //只有请求成功才会返回数据
                return res.text()
            } else {
                throw new Error(`status: ${res.status}`)
            }
            }, err => {

        }).then(d => {
            if (d === undefined || d === '') {
                return
            }
        })
        .catch(err => {
            console.log(err)
        })
    }

    return (
        <div>

            <Menu mode="horizontal">
                <Menu.Item
                    key='delApp'
                    danger={true}
                    icon={<RestOutlined />}
                    onClick={() => {
                        confirm({
                            title: '确认删除此APP？',
                            icon: <ExclamationCircleOutlined />,
                            content: '删除后无法进行恢复',
                            okText: '删除',
                            cancelText: '取消',
                            onOk() {
                                delApp()
                            },
                            onCancel() {
                                console.log('取消删除');
                            },
                        });
                    }}
                >
                    删除APP
                </Menu.Item>
                <Menu.Item
                    key='addFun'
                    icon={<PlusCircleOutlined />}
                    onClick={() => {
                        setVisible(true);
                    }}
                >
                    添加功能
                </Menu.Item>
                {
                    props.appFunList.map((item, index) => {
                        return (
                            <Menu.Item
                                key={item.name}
                                icon={<MailOutlined />}
                            >
                                <NavLink to={routes[index].path}>
                                    {item.name}
                                </NavLink>
                            </Menu.Item>
                        )
                    })
                }

            </Menu>

            <CollectionCreateForm
                visible={visible}
                onCreate={onCreate}
                onCancel={() => {
                    setVisible(false);
                }}
            />

            <Switch>
                {
                    routes.map((item, idx) => (
                        <Route key={idx} path={item.path} component={item.component} />
                    ))
                }
            </Switch>
        </div>
    )
}
const mapStateToProps = (state) => ({
    applist: state.applist.data,
    appFunList: state.appFunList.data,
})

export default withRouter(connect(mapStateToProps)(AppDetail));
